import config from './_config.js';
import axios from 'axios';
import multer from 'multer';
import FormData from 'form-data'
import path from 'path';
const storage = multer.memoryStorage()
const upload = multer({
  storage: storage, fileFilter: function (req, file, cb) {
    const suffix = path.extname(file.originalname);
    if(suffix != '.torrent' && suffix != '.TORRENT') {
      cb(null, false);
    }
    else {
      cb(null, true);
    }
  }
});

export async function post(req, res) {
  const uploadCb = upload.single('file')
  uploadCb(req, res, async function (err) {
    if (err instanceof multer.MulterError) {
      res.writeHead(500);
      res.end('A Multer error occurred when uploading.');
      return;
    } else if (err) {
      res.writeHead(500);
      res.end('An unknown error occurred when uploading.');
      return;
    }
    const host = config.host;
    res.writeHead(200, {
      'content-type': 'text/plain;charset=utf8'
    });
    const token = req.session.token;
    if (!token) {
      return false;
    }
    if(!req.file) {
      return res.end(JSON.stringify({
        success: 0,
        message: '对不起，文件类型错误！'
      }));
    }
    const buffer = req.file.buffer;
    const form  = new FormData();
    form.append('file', buffer, {filename: req.file.originalname});
    try {
      const result = await axios({
        method: 'post',
        url: host + `/api2/upload`,
        headers: {
          'Authorization': 'Bearer ' + token,
          'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`
        },
        data: form,
        dataType: 'json'
      });
      let data = result.data;
      if (data.success == 0) {
        return res.end(JSON.stringify(data));
      } else {
        return res.end(JSON.stringify(data));
      }
    } catch (error) {
      console.log(error);
      res.end(JSON.stringify({ error: error.message }));
    }
  })
}